package com.project.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.project.bean.UserBean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @RequestMapping("login")
    public String login(String userName, String pwd, HttpServletRequest request){
        if("java".equals(userName) && "123".equals(pwd)){
            request.getSession().setAttribute("loginUser",userName);
            return "ok";
        }
        else{
            return "no";
        }
    }

    @RequestMapping("add")
    public String add(String userName, MultipartFile face) throws Exception{
        //得到上传文件名
        String fileName = face.getOriginalFilename();
        //以时间毫秒数做文件名，后缀名不变，重命名上传文件，防止文件重名而覆盖
        fileName = System.currentTimeMillis() +
                fileName.substring(fileName.lastIndexOf("."));

        //将上传文件的二进制数据，保存到指定文件中
        face.transferTo(new File("E:/J192WEB/interceptorTest/image/"+fileName));
        return userName+"   "+fileName;
    }


    @RequestMapping("uploadExcel")
    public String upload(MultipartFile excelFile) throws Exception{
        //初始化设置
        ImportParams params = new ImportParams();
        //设置读取第几个选项卡
        params.setSheetNum(1);
        //设置表头占几行
        params.setHeadRows(1);
        //设置标题栏占几行
        params.setTitleRows(1);

        //将上传excel数据，封装成用户集合
        //第一个参数为上传文件读取流，第二个参数为要封装实体对象的类模版
        //第三个参数为初始化对象
        List<UserBean> list = ExcelImportUtil.importExcel(
                excelFile.getInputStream(), UserBean.class,params);
        System.out.println(list);
        return "ok";
    }
}
